package com.unchartedskies.view
{
	import com.gamesmile.framework.util.Log;
	import com.unchartedskies.controller.event.PlayerIOEvent;
	import com.unchartedskies.controller.event.StateEvent;
	import com.unchartedskies.controller.event.TransitionEvent;
	import com.unchartedskies.factory.StateFactory;
	import com.unchartedskies.model.value.StateConstant;
	
	import flash.display.Sprite;
	
	import org.robotlegs.mvcs.Mediator;
	
	public class MainMediator extends Mediator
	{
		[Inject]
		public var view:Main;
		
		private var currentView:Sprite;
		private var previousView:Sprite;
		
		public function MainMediator()
		{
			super();
		}

		override public function onRegister():void
		{
			Log.debug(this,"Register");
			addContextListener(StateEvent.CHANGE_STATE, changeState);
			addViewListener(TransitionEvent.TRANSITION_INITIAL,onTransitionInitial,TransitionEvent);
			addViewListener(TransitionEvent.TRANSITION_COMPLETE, onTransitionComplete, TransitionEvent);
			
			//PlayerIO Event
			addContextListener(PlayerIOEvent.CONNECTING,onPlayerIOConnecting,PlayerIOEvent);  
			addContextListener(PlayerIOEvent.CONNECTED, onPlayerIOConnected, PlayerIOEvent);
			
			currentView = StateFactory.createView(StateConstant.STATE_ACCUEIL);
			view.displayView(currentView);
		}
		
		/**
		 * Change la state 
		 * @param e
		 * 
		 */		
		private function changeState(e:StateEvent):void
		{
			Log.debug(this,"Changing state : "+e.stateName);
			//Active le mask de chargement
			view.displayLoadingMask();
			
			//Stock la vue précédente
			previousView = currentView;
			
			//Créé la nouvelle vue
			currentView = StateFactory.createView(e.stateName);
			
			//Active les panneaux de transition
			view.displayAndStartPannelTransition(contextView.height);
		}
		/**
		 * Gère le switch de vue après fin d'animation des panneaux 
		 * @param e
		 * 
		 */		
		private function onTransitionInitial(e:TransitionEvent):void
		{
			Log.debug(this,"Transition initial");	
			//Affiche la nouvelle vue
			view.displayView(currentView);
			
			//Supprime l'ancienne vue
			view.removeView(previousView);
			previousView = null;
			
			//Retire les panneaux
			view.removePannelTransition(contextView.height);
		}
		private function onTransitionComplete(e:TransitionEvent):void
		{
			Log.debug(this,"Transition complete");
			//Retire le mask de chargement
			view.removeLoadingMask();
			
		}
		/**
		 * Affichage du mask quand on se connect à playerIO 
		 * @param e
		 * 
		 */		
		private function onPlayerIOConnecting(e:PlayerIOEvent):void
		{
			Log.debug(this,"PLAYERIO CONNECTING");
			view.displayLoadingMask();
		}
		
		/**
		 * Connection effectué à playerIO
		 * */
		private function onPlayerIOConnected(e:PlayerIOEvent):void
		{
			
		}
	}
}